package cn.jjxx.modules.oss.controller;

import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.SpringContextHolder;
import cn.jjxx.modules.sys.entity.User;
import cn.jjxx.modules.sys.security.shiro.web.filter.authc.FormAuthenticationFilter;
import cn.jjxx.modules.sys.security.shiro.web.filter.authc.UsernamePasswordToken;
import cn.jjxx.modules.sys.service.IUserService;
import cn.jjxx.modules.sys.service.impl.PasswordService;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.util.WebUtils;
import org.framework.customutil.endecryption.aes.AESHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: java类作用描述
 * @Param:
 * @Author: fengshisheng
 * @CreateDate: 2018/6/15 9:45
 */

@Controller
@RequestMapping("${admin.url.prefix}/sso")
public class OSSController {
    @Autowired
    private IUserService userService;
    @Autowired
    private SecurityManager securityManager;
    
    private static String SALT_KEY = null;

    /**
     * @ProjectName: 单点登录认证
     * @Description: java类作用描述
     * @Param: * @param null
     * @Author: fengshisheng
     * @CreateDate: 2018/6/20 10:27
     * @Version: 1.0
     */
    @RequestMapping(value = "/toAuth", method = RequestMethod.GET)
    @ResponseBody
    public String toAuth(String key, HttpServletRequest request, HttpServletResponse response) throws IOException {
    	SALT_KEY = MessageUtils.getMessage("oss.salt.key");
    	String b = "true";
        String uerId = "";
        String string = "";
        String type = "-1";//-1：成功；0：用户不存在；1：密码错误；2：系统认证异常；3:系统登录异常；
        try {
            if (key.length() > SALT_KEY.length()) {
                string = key.substring(0, key.length() - SALT_KEY.length());
            }
            if (null != string) {
                String UPwd = AESHelper.AESDncode(SALT_KEY, string);
                String[] arr = UPwd.split("\\|");
                if (arr.length > 1) {
                    EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
                    userEntityWrapper.eq("username", arr[0]);
                    List<User> users = userService.selectList(userEntityWrapper);
                    if (users.size() > 0) {
                        User user = users.get(0);
                        String newPassword = new SimpleHash(PasswordService.mName, arr[1],
                                ByteSource.Util.bytes(user.getCredentialsSalt()), PasswordService.anInt).toHex();
                        if (user.getPassword().equals(newPassword)) {
                            uerId = AESHelper.AESEncode(SALT_KEY, user.getId());
                        } else {
                            b = "false";
                            type = "1";
                        }
                    } else {
                        b = "false";
                        type = "0";
                    }
                } else {
                    b = "false";
                    type = "0";
                }
            } else {
                b = "false";
                type = "0";
            }
        } catch (Exception e) {
            b = "false";
            type = "2";
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success", b);
        map.put("userId", uerId);
        map.put("type", type);
        String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数
        return jsonpCallback + "(" + JSON.toJSONString(map) + ")";
    }

    /**
     * @ProjectName: 单点登录
     * @Description: java类作用描述
     * @Param: * @param null
     * @Author: fengshisheng
     * @CreateDate: 2018/6/20 10:27
     * @Version: 1.0
     */
    @RequestMapping(value = "/toSSO", method = RequestMethod.GET)
    @ResponseBody
    public String toSSO(String key, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException, ServletException {
    	SALT_KEY = MessageUtils.getMessage("oss.salt.key");
    	String b = "true";
        User user = new User();
        String type = "-1";//-1：成功；0：用户不存在；1：密码错误；2：系统认证异常；3:系统登录异常；
        String isMobile = request.getParameter("mobile");
        boolean boo = false;
        if ("true".equals(isMobile)) {
            boo = true;
        }
        if (key != null && !"".equals(key)) {
            String id = AESHelper.AESDncode(SALT_KEY, key);
            if (id.length() > 1) {
                user = userService.selectById(id);
                if (user != null) {
                    try {
                        //得到SecurityManager实例 并绑定给SecurityUtils
                        SecurityUtils.setSecurityManager(securityManager);
                        Subject subject = SecurityUtils.getSubject();
                        //得到Subject及创建用户名/密码身份验证Token（即用户身份/凭证）
                        InetAddress address = InetAddress.getLocalHost();//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
                        String hostAddress = address.getHostAddress();//192.168.0.121
                        String captcha = WebUtils.getCleanParam(request, (SpringContextHolder.getBean(FormAuthenticationFilter.class).getCaptchaParam()));
                        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword().toCharArray(), false, hostAddress, captcha, boo, "sso");
                        //登录，即身份验证
                        subject.login(token);
                    } catch (Exception e) {
                        b = "false";
                        type = "3";
                    }

                } else {
                    b = "false";
                    type = "0";
                }
            }
        } else {
            b = "false";
            type = "0";
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success", b);
        map.put("type", type);
        String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数
        return jsonpCallback + "(" + JSON.toJSONString(map) + ")";
    }

}
